<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="rolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色表单 -->
      <el-table :data="rolesList" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二、三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning" closable @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="acquireRoles(scope.row.id)"
            >编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRoles(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRight(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="rolesDialogVisible"
        width="50%"
        @close="resetRolesForm"
      >
        <!-- 主体区域 -->
        <el-form :model="storageRoles" :rules="rolesRules" ref="rolesRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="storageRoles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="storageRoles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer">
          <el-button @click="rolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog title="编辑角色" :visible.sync="redactVisible" width="50%" @close="resetRedactForm">
        <el-form :model="redactRolesList" :rules="rolesRules" ref="redactRolesRef" label-width="100px">
            <el-form-item label="角色id">
                <el-input v-model="redactRolesList.roleId" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="redactRolesList.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="redactRolesList.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="redactVisible = false">取 消</el-button>
          <el-button type="primary" @click="redactRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="提示" :visible.sync="showSetRightVisible" width="50%" @close="resetShowTree">
        <!-- 树形主体区域 -->
        <el-tree :data="rolesTree" :props="TreeProps" show-checkbox node-key="id"
        default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showSetRightVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAllocation">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取数据库角色表单数据
      rolesList: [],
      // 是否显示隐藏添加角色对话框
      rolesDialogVisible: false,
      // 存储角色表单数据
      storageRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 校验角色规则
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 6,
            message: '角色名称的长度在2~6个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 4,
            max: 8,
            message: '角色名称的长度在4~8个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 是否显示隐藏编辑角色对话框
      redactVisible: false,
      // 获取数据库编辑角色数据
      redactRolesList: [],
      // 是否显示隐藏分配权限对话框
      showSetRightVisible: false,
      // 获取数据库树形权限列表
      rolesTree: [],
      // 树形控件的属性绑定对象
      TreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取数据库角色数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 重置角色表单
    resetRolesForm () {
      this.$refs.rolesRef.resetFields()
    },
    // 添加角色
    addRoles () {
      this.$refs.rolesRef.validate(async val => {
        if (!val) return
        // 成功
        const { data: res } = await this.$http.post('roles', this.storageRoles)
        if (res.meta.status !== 201) {
          return this.$message.error('创建失败')
        }
        this.$message.success(res.meta.msg)
        this.rolesDialogVisible = false
        this.getRolesList()
      })
    },
    // 获取编辑角色id
    async acquireRoles (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.redactRolesList = res.data
      this.redactVisible = true
      console.log(this.redactRolesList)
    },
    // 重置编辑表单
    resetRedactForm () {
      this.$refs.redactRolesRef.resetFields()
    },
    // 编辑角色
    redactRoles () {
      this.$refs.redactRolesRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put('roles/' + this.redactRolesList.roleId, {
          roleName: this.redactRolesList.roleName,
          roleDesc: this.redactRolesList.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }
        this.redactVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    async delRoles (id) {
      const confirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirm !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    },
    // 权限删除
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      role.children = res.data
    },
    // 分配权限
    async showSetRight (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolesTree = res.data

      // 递归获取三级权限的Id
      this.getLeafKeys(role, this.defKeys)
      this.showSetRightVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 重置分配权限
    resetShowTree () {
      this.defKeys = []
    },
    // 提交分配权限
    async subAllocation () {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = key.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keyStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.showSetRightVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
